package fi.foyt.cs.android.ui;

import java.io.IOException;

import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.AndroidRuntimeException;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import fi.foyt.cs.android.client.CriminalSoulsClient;

public class LoginActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   
    WebViewClient webViewClient = new WebViewClient() {
      @Override
      public void onPageFinished(WebView view, String url) {
        if (!CriminalSoulsClient.getInstance().isAuthorized()) {
          String successUrl = CriminalSoulsClient.getInstance().getRedirectUrl() + "?code=";
          String errorUrl = CriminalSoulsClient.getInstance().getRedirectUrl() + "?error=";
          
          if (url.startsWith(errorUrl)) {
            String error = url.substring(successUrl.length() + 1);
            
            throw new AndroidRuntimeException(error);

          } else if (url.startsWith(successUrl)) {
            String code = url.substring(successUrl.length());
            try {
              CriminalSoulsClient.getInstance().authorize(code);
              backToMain();
            } catch (JSONException e) {
              throw new AndroidRuntimeException(e);
            } catch (IOException e) {
              throw new AndroidRuntimeException(e);
            }
          }
        }

        super.onPageFinished(view, url);
      }
      
      @Override  
      public boolean shouldOverrideUrlLoading(WebView view, String url) {  
        view.loadUrl(url);  
        return true;  
      }  
    };
    
    webview = new WebView(this);
    webview.setWebViewClient(webViewClient);
    setContentView(webview);
  }
  
  @Override
  protected void onStart() {
    super.onStart();

    webview.loadUrl(CriminalSoulsClient.getInstance().getAuthorizationUrl());
  }
  
  private void backToMain() {
    Intent mainIntent = new Intent(this, MainActivity.class);
    startActivity(mainIntent);
  }
  
  private WebView webview;
}
